package general;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;

/**
 * @Author if
 * @Description: 同步生产者
 * @Date 2021-10-24 下午 05:52
 */
public class SyncProducer {
    public static void main(String[] args) throws MQClientException, RemotingException, InterruptedException, MQBrokerException {
        //创建一个producer，参数为producerGroup名称
        DefaultMQProducer producer=new DefaultMQProducer("pg");
        //设置name server地址
        producer.setNamesrvAddr("centos:9876");
        //启动生产者
        producer.start();

        //当发送失败时重试发送的次数，默认2次
        producer.setRetryTimesWhenSendFailed(3);
        //设置发送超时时间5000ms（5s），默认3000ms
        producer.setSendMsgTimeout(5000);

        //测试生产并发送100条消息
        for(int i=0;i<100;i++){
            byte[] body=("Hi,"+i).getBytes();
            //创建Message，指定topic、tag和具体内容byte[]类型的body
            Message msg=new Message("someTopic","someTag",body);
            //发送消息并获得result
            SendResult sendResult = producer.send(msg);
            System.out.println(sendResult);
        }
        //关闭producer
        producer.shutdown();
    }
}
